package com.fen.service.lmpl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fen.dao.HeadPortraitMapper;
import com.fen.pojo.HeadPortrait;
import com.fen.service.HeadPortraitService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

/**
 * @Description: springbootsc
 * @Author: lijiafen
 * @Date: 2021/12/15
 * @Time: 15:26
 * @eamil: 2368044269@qq.com
 */
@Service
public class HeadPortraitServicelmpl extends ServiceImpl<HeadPortraitMapper, HeadPortrait> implements HeadPortraitService {
    @Autowired
    HeadPortraitMapper mapper;

    @Value("${exhibit.resource.path}")
    private String resourcePath;
    @Override
    /**
    * @Description: 用户上传头像
    * @Author: lijiafen
    */
    public int inlmg(Integer id, MultipartFile file) {
        String path= DateTimeFormatter.ofPattern("yyyy/MM/dd")
                .format(LocalDate.now());
        File folder=new File(resourcePath,path);
        if (!folder.exists()) {
            //创建这个路径
            folder.mkdirs();
        }
        String fileName = file.getOriginalFilename();
        String ext = fileName.substring(
                fileName.lastIndexOf("."));
        //声成UUID字符串,并确定文件名
        String name = UUID.randomUUID() + ext;
        File file1 = new File(folder, name);
        //执行上传
        try {
            file.transferTo(file1);
        } catch (IOException e) {
            e.printStackTrace();
        }
        HeadPortrait image = new HeadPortrait();
        image.setUserId(id);
        image.setUrlImg("/"+path+"/"+name);
        int i;
        return i = mapper.insert(image);
    }

    /**
    * @Description: 用户修改头像
    * @Author: lijiafen
    */
    @Override
    public int updateimg(Integer id, MultipartFile file) {
        String path= DateTimeFormatter.ofPattern("yyyy/MM/dd")
                .format(LocalDate.now());
        File folder=new File(resourcePath,path);
        if (!folder.exists()) {
            //创建这个路径
            folder.mkdirs();
        }
        String fileName = file.getOriginalFilename();
        String ext = fileName.substring(
                fileName.lastIndexOf("."));
        //声成UUID字符串,并确定文件名
        String name = UUID.randomUUID() + ext;
        File file1 = new File(folder, name);
        //执行上传
        try {
            file.transferTo(file1);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //这里我们用传过来的id查询
        HeadPortrait image = mapper.selectById(id);
        System.out.println(image);
        //重新注入路径
        image.setUrlImg("/"+path+"/"+name);
         int i = mapper.updateById(image);
         return i;
    }
}
